#!/usr/bin/python3
from openpyxl import load_workbook
from openpyxl.worksheet.datavalidation import DataValidation
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Composite_Amend(Base_Plugin):
    """复合类型数据表类型修正插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context
        self.project_config_sheet_name = "工程配置"
        self.composite_type_config_start_col = 2
        self.composite_type_mapping_start_col = 3
        self.composite_type_mapping = dict()

    def get_composite_config(self, sheet):
        """
        读取复合类型配置
        """
        for row in sheet.rows:
            if row[0].row < self.project_config["通用开始行"]:
                continue

            composite_type = row[self.composite_type_config_start_col].value
            if composite_type is None:
                break
            composite_type_mapping = row[self.composite_type_mapping_start_col].value
            assert row[2].value in row[3].value, self.error_log(
                f"""{row[2].value}配置无效"""
            )
            self.composite_type_mapping[composite_type] = composite_type_mapping.split(
                "-"
            )[1]

    def amend_composite_type(self, sheet):
        """
        修正复合类型数据表字段类型
        """
        for row in sheet.rows:
            if row[0].row < self.project_config["列字段开始行"]:
                continue
            if row[8].value in self.composite_type_mapping.keys():
                if row[2].value != self.composite_type_mapping[row[8].value]:
                    row[2].value = self.composite_type_mapping[row[8].value]
                    self.processed += 1

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        _project_config = workbook[self.project_config_sheet_name]
        self.get_composite_config(_project_config)

        for row in _directory.rows:
            if row[0].row < self.project_config["通用开始行"]:
                continue
            table_name = row[1].value
            table_name = table_name.strip()
            table_description = row[2].value.strip()

            if table_description in workbook.sheetnames:
                sheet = workbook[table_description]
                self.amend_composite_type(sheet)

        return_val = None
        if self.processed > 0:
            saved_name = r"SheetsCompositeAmend.xlsx"
            new_path = os.path.join(workspace, saved_name)
            if os.path.exists(new_path):
                os.remove(new_path)
            workbook.save(new_path)
            return_val = saved_name
        else:
            return_val = source
        del workbook
        gc.collect()
        return return_val
